package Presenter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;
import Models.Documents;

public class DocumentPresenter extends AbstractPresenter<Documents> {
	final String SINGLEITEM = "documents";
	final String MULTIITEM = "documentss";
	
	public ArrayList<Documents> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public Documents tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public Documents createItemFromJSONObject(JSONObject jsonObject){
		Documents doc = new Documents();
		try{
			doc.setDocID(jsonObject.getInt("id"));
			doc.setDocData(jsonObject.getInt("docData"));
			doc.setDocDate(timeFormat.parse(jsonObject.getString("date")));
			doc.setDocRevision(jsonObject.getInt("docRevision"));
			doc.setDocType(jsonObject.getInt("docType"));
			doc.setDocVersion(jsonObject.getInt("version"));
			if(!jsonObject.isNull("docDescription")){
				doc.setDocDescription(jsonObject.getString("docDescription"));
			} else {
				doc.setDocDescription(null);
			}
			if(!jsonObject.isNull("docExt")){
				doc.setDocExtension(jsonObject.getString("docExt"));
			} else {
				doc.setDocExtension(null);
			}
			if(!jsonObject.isNull("documents")){
				DocumentPresenter presenter = new DocumentPresenter();
				JSONObject jsonGroup = jsonObject.getJSONObject("documents");
				doc.setDocPrev(presenter.createItemFromJSONObject(jsonGroup));
			} else {
				doc.setDocPrev(null);
			}
			return doc;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(Documents item){
		try{
			JSONObject json = new JSONObject();
			json.put("id", item.getDocID());
			json.put("docData", item.getDocData());
			json.put("date", getDate(item.getDocDate()));
			json.put("docRevision", item.getDocRevision());
			json.put("docType", item.getDocType());
			json.put("version", item.getDocVersion());
			if(item.getDocDescription()!=null){
				json.put("docDescription", item.getDocDescription());
			} else {
				json.put("docDescription", JSONObject.NULL);
			}
			if(item.getDocExtension()!=null){
				json.put("docExt", item.getDocExtension());
			} else {
				json.put("docExt", JSONObject.NULL);
			}
			if(item.getDocPrev()!=null){
				DocumentPresenter presenter = new DocumentPresenter();
				json.put("documents", presenter.createJSON(item.getDocPrev()));
			} else {
				json.put("documents", JSONObject.NULL);
			}
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public Documents getEmptyEntity(){
		Documents entity = new Documents();
		return entity;
	}
}
